Page({
  data: {
    issueNumber: '',    // 期号
    drawDate: '',       // 开奖日期
    redBalls: [],       // 红球号码
    blueBall: '',       // 蓝球号码
    updateTime: '',     // 更新时间
    isLoading: true     // 加载状态
  },

  onLoad() {
    this.fetchLotteryData();
  },

  // 获取开奖数据
  fetchLotteryData() {
    // 显示加载动画
    this.setData({ isLoading: true });
    
    wx.request({
      url: 'https://jfb.teampanel.cn/api/caipiao/latest',
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          const data = res.data.result;
          // 解析号码
          const allNumbers = data.number.split('|');
          const redBalls = allNumbers.slice(0, 6);
          const blueBall = allNumbers[6];
          
          this.setData({
            issueNumber: data.qihao,
            drawDate: data.time,
            redBalls: redBalls.sort((a, b) => a - b), // 红球排序
            blueBall: blueBall,
            updateTime: this.formatDateTime(new Date())
          });
          
          // 模拟球的掉落动画
          this.animateBalls();
        } else {
          wx.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 格式化日期时间
  formatDateTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  // 球的动画效果
  animateBalls() {
    const query = wx.createSelectorQuery();
    
    // 获取所有球元素
    query.selectAll('.ball').boundingClientRect(rects => {
      rects.forEach((rect, index) => {
        const animation = wx.createAnimation({
          duration: 500 + index * 100,
          timingFunction: 'ease-out'
        });
        
        // 初始位置
        animation.translateY(-300).opacity(0).step();
        
        // 最终位置
        animation.translateY(0).opacity(1).step();
        
        // 应用动画
        const animationData = animation.export();
        const ballClass = `.ball:nth-child(${index + 1})`;
        this.setData({
          [`ballAnimations[${index}]`]: animationData
        });
      });
    }).exec();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.fetchLotteryData();
    wx.stopPullDownRefresh();
  }
});    